package com.example.common.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

/**
 * @author skygge
 * @date 2020/7/30.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：包含ViewDataBinding层的基类
 */
public class BaseBindFragment<B extends ViewDataBinding> extends BaseFragment{

    protected B mDBind;

    private View mView;

    public BaseBindFragment() {
        // Required empty public constructor
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getLayoutId()>0 && mView == null){
            mDBind = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);
            mView = mDBind.getRoot();
        }
        // 缓存View判断是否含有parent, 如果有需要从parent删除, 否则发生已有parent的错误.
        ViewGroup parent = (ViewGroup) mView.getParent();
        if (parent != null) {
            parent.removeView(mView);
        }
        return mView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mView != null) {
            ((ViewGroup) mView.getParent()).removeView(mView);
        }
    }
}
